<template>
  <el-form v-loading.body="listLoading" :model="ruleForm" ref="ruleForm" label-position="right"  label-width="100px" class="small-space">
    <el-row>
      <el-col :span="12" :offset="1">
        <el-form-item label="姓名" prop="name">
          <el-input size="small" v-model="ruleForm.name"></el-input>
          <transition name="el-zoom-in-top">
            <div class="el-form-item__error" v-if="errors.name">{{errors.name ? errors.name[0] : ''}}</div>
          </transition>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="age">
          <el-date-picker
            v-model="ruleForm.birthday"
            type="date"
            placeholder="选择日期"
            @change="pickerChange"
          >
          </el-date-picker>
          <transition name="el-zoom-in-top">
            <div class="el-form-item__error" v-if="errors.birthday">{{errors.birthday ? errors.birthday[0] : ''}}</div>
          </transition>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input size="small" v-model="ruleForm.mobile"></el-input>
          <transition name="el-zoom-in-top">
            <div class="el-form-item__error" v-if="errors.mobile">{{errors.mobile ? errors.mobile[0] : ''}}</div>
          </transition>
        </el-form-item>
        <el-form-item label="工作信息" prop="job">
          <el-select
            v-model="ruleForm.job"
            multiple
            filterable
            allow-create
            placeholder="请选择文章标签">
            <el-option
              @change="jobChange"
              v-for="item in extraInfo.job"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <transition name="el-zoom-in-top">
            <div class="el-form-item__error" v-if="errors.job">{{errors.job ? errors.job[0] : ''}}</div>
          </transition>
        </el-form-item>
        <el-form-item label="住址" prop="">
          <el-cascader :options="options" v-model="selectedOptions" @change="handleChange"></el-cascader>
        </el-form-item>
      </el-col>
      <el-col :span="6" :offset="1">
        <template v-if="photo">
          <img :src="photo" alt="" style="width: 250px;height: 250px">
          <div class="p-button">
            <el-button type="primary" @click="photoStorge = photo;photo = null">重新拍照</el-button>
            <el-button type="primary" @click="uploadPhoto">上传</el-button>
          </div>
        </template>
        <template v-else>
          <webcam ref='webcam' :width="250" :height="250"></webcam>
          <div class="p-button">
            <el-button type="primary" @click="take_photo">拍照</el-button>
            <el-button type="primary" @click="photo = photoStorge;photoStorge = null">关闭摄像头</el-button>
          </div>
        </template>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="20" :offset="1">
        <el-form-item label="详细住址" prop="">
          <el-input size="small" v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="9">
            <el-form-item  label="卡种">
              <el-select size="small" v-model="ruleForm.cards_type_id" filterable placeholder="卡种(可搜索)">
                <el-option v-for="item in extraInfo.card_type.data" :label="item.title" :value="item.id" :key="item.id"></el-option>
              </el-select>
              <transition name="el-zoom-in-top">
                <div class="el-form-item__error" v-if="errors.cards_type_id">{{errors.cards_type_id ? errors.cards_type_id[0] : ''}}</div>
              </transition>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9">
            <el-form-item  label="责任会籍">
              <el-select size="small" v-model="ruleForm.saleman_uuid" filterable placeholder="责任会籍(可搜索)" @change="membershipChange">
                <el-option v-for="item in extraInfo.saleman.data" :label="item.realname" :value="item.uuid" :key="item.uuid"></el-option>
              </el-select>
              <transition name="el-zoom-in-top">
                <div class="el-form-item__error" v-if="errors.saleman_uuid">{{errors.saleman_uuid ? errors.saleman_uuid[0] : ''}}</div>
              </transition>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="责任教练">
          <el-select size="small" v-model="ruleForm.coach_uuid" placeholder="责任教练">
            <el-option v-for="item in extraInfo.coach.data" :label="item.realname" :value="item.uuid" :key="item.uuid"></el-option>
          </el-select>
          <transition name="el-zoom-in-top">
            <div class="el-form-item__error" v-if="errors.coach_uuid">{{errors.coach_uuid ? errors.coach_uuid[0] : ''}}</div>
          </transition>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
  import _ from 'lodash'
  import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
  import Webcam from 'components/Webcam'
  import { data2blob } from '@/utils/index'
  import { upLoad, ShowUser, extraInfo, CreateCard } from '@/api/member'

  export default{
    components: {
      Webcam
    },
    props: {
      dialogFormShow: {
        type: Boolean,
        default: false
      },
      checkId: {
        default: null
      }
    },
    data () {
      return {
        errors: {},
        floorPrice: 5,
        listLoading: false,
        dialogFormVisible: true,
        options: regionData,
        photo: null,
        photoStorge: null, //原始头像暂存区
        extraInfo: {
          saleman:{
            data: []
          },
          coach: {
            data: []
          },
          card_type: {
            data: []
          },
          job: []
        },
        ruleForm: {
          mobile: null,
          name: 'aaaaa',
          sex: '男',
          birthday: null,
          province: "广东省",
          city: "广州市",
          area: "番禺区",
          address: null,
          active_date: null,
          card_type: null,
          start_date: null,
          end_date: null,
          times: 50,
          clock_start_time: null,
          clock_end_time: null,
          coach_uuid: null,
          saleman_uuid: null,
          cards_type_id: null,
          job: []
        }
      }
    },
    watch: {
      checkId (value, oldvalue) {
        this.createThis(this.checkId)
      }
    },
    methods: {
      uploadPhoto () {
        let formData = new FormData()
        formData.append('file', data2blob(this.photo),`avatar-${this.ruleForm.name}`)
        console.log('formData', formData)
        upLoad(formData).then( (res) => {
          this.ruleForm.avatar_id = res.id
          this.$message({ type:'success', message:'照片上传成功'})
          this.openWebcam = false
        })
      },
      jobChange(e){
        console.log('job')
        console.log('job', this.ruleForm.job)
      },
      membershipChange(v) {
        console.log(v)
      },
      take_photo () {
        this.photo = this.$refs.webcam.getPhoto();
      },
      pickerChange(v){
        this.ruleForm.birthday = v
      },
      submitForm(formName){
        this.listLoading = true
        console.log('debug--->this.ruleForm', this.ruleForm)
        this.$refs[formName].validate((valid) => {
          CreateCard(this.ruleForm).then((res) => {
            this.$message({message: '开卡成功', type: 'success'})
            this.listLoading = false
            this.dialogFormShow = false
            this.reloadList()
            this.resetForm('ruleForm')
          }).catch((error) => {
            const { response, request, config } = error
            this.errors = response.data.errors
            this.listLoading = false
          })
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleChange (value) {
        console.log('value', value)
      },
      reloadList () {
        this.$emit('updateCardReloadList')
      },
      createThis(){
        this.errors = {}
        this.listLoading = true
        extraInfo().then((res) => {
          this.extraInfo = res
          ShowUser(this.checkId).then(({data}) =>{
            const avatar_id = data.avatar.data.id
            this.photo =  data.avatar.data.url
            data = _.pick(data, ['name', 'mobile', 'sex', 'birthday', 'job', 'province', 'city', 'area', 'address'])
            data = _.assignIn(data, {cards_type_id: null}, {saleman_uuid: null}, {coach_uuid: null}, {avatar_id})
              const citys = ['北京市', '上海市', '天津市', '重庆市']
            citys.forEach((city) => {
              if (data.province === city) {
                data.city = '市辖区'
              }
              console.log('for city', data.province, city,data.city)
            })
            this.ruleForm = data
            console.log('this.ruleForm', this.ruleForm, data)
            this.listLoading = false
          })
        })
      }
    },
    computed: {
      selectedOptions: {
        get(value){
          let r = value.ruleForm
          let array = [TextToCode[r.province]['code'],
            TextToCode[this.ruleForm.province][this.ruleForm.city]['code'],
            TextToCode[this.ruleForm.province][this.ruleForm.city][this.ruleForm.area]['code']]
          return array
        },
        set (value) {
          this.ruleForm.province = CodeToText[value[0]]
          this.ruleForm.city = CodeToText[value[1]]
          this.ruleForm.area = CodeToText[value[2]]
        },
      }
    },
    mounted(){
      this.createThis()
    }
  }
</script>

<style scoped>
  .el-col-12 .el-form-item{
    margin-bottom: 17px;
  }
  .p-button{
    width: 250px; text-align: center;padding-top: 20px
  }
</style>
